<?php
namespace User\Controller;
use Think\Controller;
class AjaxController extends Controller {
    public function index(){
    }

    public function captcha(){
		$Verify = new \Think\Verify(array(
			'fontSize'    =>    20,    // 验证码字体大小
			'length'      =>    4,     // 验证码位数
			'useNoise'    =>    false, // 关闭验证码杂点
			'codeSet'     =>	'0123456789'
		));
		$Verify->entry();
	}

    public function ajax_login(){
		$post_data = get_json();
		if($post_data && isset($post_data['username']) && isset($post_data['password']) && isset($post_data['captcha'])){
			if(check_verify($post_data['captcha'])){
				$result = M('admin')->field('id,password,salt')->where(array('username'=>$post_data['username']))->find();
				if($result && $result['password'] === pwd_encrypt($post_data['password'] , $result['salt'])){
					session('username',  $post_data['username']);
					print_json(array('error' => 0, 'msg'=>'登录成功'));
				}else{
					print_json(array('error' => 2, 'msg'=>'用户名或密码错误'));
				}
			}else{
				print_json(array('error' => 3, 'msg'=>'验证码错误'));
			}
		}else{
			print_json(array('error' => 1, 'msg'=>'参数错误'));
		}
	}

    public function ajax_logout(){
        session(null);
		print_json(array('error' => 1, 'msg'=>'参数错误'));
	}

	public function ajax_repass(){
		if(session('?username')){
            $post_data = get_json();
            if(!empty($post_data['newpass']) && !empty($post_data['re_newpass'])){
				if($post_data['newpass'] === $post_data['re_newpass']){
					$salt = random_string(6);
					$newpasswd = pwd_encrypt($post_data['newpass'] , $salt);
					if(M('admin')->where(array('username'=>session('username')))->save(array('password'=> $newpasswd, 'salt'=>$salt)) != false){
						print_json(array('error' => 0, 'msg'=>'密码修改成功'));
					}else{
						print_json(array('error' => 3, 'msg'=>'密码修改失败'));
					}
				}else{
					print_json(array('error' => 3, 'msg'=>'两次输入的密码不匹配'));
				}
            }else{
                print_json(array('error' => 1, 'msg'=>'参数错误'));
            }
        }else{
            print_json(array('error' => 2, 'msg'=>'没有权限，请登录后使用'));
        }
	}
}